package com.haibara.codesubmiteval.chain.redisRunnerChain;

import com.haibara.codesubmiteval.constant.AuthConstant;
import com.haibara.codesubmiteval.constant.RedisKeyConstant;
import com.haibara.codesubmiteval.model.entity.User;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.annotation.Order;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.Set;
import java.util.stream.Collectors;

/**
 * 系统中普通用户id集合
 *
 * @Author: mengyu
 * @Date: 2025/4/29
 */
@Order(5)
@Component
@Slf4j
public class CommonUserIdsInitHandler extends RedisInitHandler {
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public void handleRedisInit(RedisInitContext context) {
        Set<String> commonUserIdSet = context.getUsers().stream().
                filter(u -> AuthConstant.USER.equals(u.getUserRole())).
                map(User::getId)
                .map(Object::toString)
                .collect(Collectors.toSet());
        if (!commonUserIdSet.isEmpty()) {
            stringRedisTemplate.opsForSet().add(
                    RedisKeyConstant.getCompleteKey(
                            RedisKeyConstant.commonUserIds
                    ),
                    commonUserIdSet.toArray(new String[0])
            );
        }
        log.info("RedisInit - CommonUserIds完成");
        if (next != null) next.handleRedisInit(context);

    }
}
